package org.lt.cj.translate;

/**
 * @author zgh
 */
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class GoogleTranslate {

    private static HttpPost httppost;
    private static HttpResponse response;
    private static final DefaultHttpClient httpclient = new DefaultHttpClient();

    public static String translate(String text, String lanFrom, String lanTo) {
        List<NameValuePair> qparams = new ArrayList<NameValuePair>();


        qparams.add(new BasicNameValuePair("eotf", "1"));
        qparams.add(new BasicNameValuePair("file", ""));
        qparams.add(new BasicNameValuePair("hl", "zh-CN"));
        qparams.add(new BasicNameValuePair("ie", "UTF-8"));
        qparams.add(new BasicNameValuePair("js", "n"));
        qparams.add(new BasicNameValuePair("layout", "2"));
        qparams.add(new BasicNameValuePair("prev", "_t"));
        qparams.add(new BasicNameValuePair("sl", lanFrom));
        qparams.add(new BasicNameValuePair("text", text));
        qparams.add(new BasicNameValuePair("tl", lanTo));

        //http://translate.google.com/translate_t#
//		qparams.add(new BasicNameValuePair("hl", "en"));
//		qparams.add(new BasicNameValuePair("ie", "UTF-8"));
//		qparams.add(new BasicNameValuePair("sl", lanFrom));
//		qparams.add(new BasicNameValuePair("text", text));
//		qparams.add(new BasicNameValuePair("tl", lanTo));

        httppost = new HttpPost("http://translate.google.cn/#");
//		String cookie = "Cookie	PREF=ID=8daa1f767f10d1fe:U=f5ac701cf7d3f2e0:FF=0:LD=en:CR=2:TM=1277174286:LM=1289370601:S=q7yslRWEZs3uK1H8; NID=39=UO-TWo9HzzjHc-d_wYm7BVR1cH33KpqaN5h5877_i29nERA93FeG1GSuV3ZSvsOx8D-TnHKpB9m0KhZRH8U9uPwoE-arYd0bAyAlILyXZxLO2_TyGQhJpcMiOLVEuCpq; SID=DQAAAHoAAADMlGzeKhnGkbkIJ36tVO0ZPXgmQ6Cth7Oa6geyyE1WJooW8P01uKUHNrsRkjggvFMAWIWB9J5i18z0F6GjC_oV79mSwXEDGuRFGhRnDyJdid3ptjFW0pIyt4_2D6AMIqtOWF71aWdvY7IvAU1AWMNs8fBZHAOgRqtf3aCUkr36ZA; HSID=A6-YJTnhjBdFWukoR";
//		httppost.addHeader("Cookie", cookie);

        String responseBody = "";
        String content = "";
        try {
            httppost.setEntity(new UrlEncodedFormEntity(qparams, HTTP.UTF_8));
            response = httpclient.execute(httppost);
            responseBody = EntityUtils.toString(response.getEntity());

            int tmp1 = responseBody.indexOf("result_box");
            int tmp2 = responseBody.indexOf(">", tmp1);
            int tmp3 = responseBody.indexOf("</div>", tmp2);
            content = responseBody.substring(tmp2 + 1, tmp3).replaceAll("<br>",
                    "\n").replaceAll("<[^>]*>", "");
        } catch (Exception e) {
            return content;
        } finally {
            httppost.abort();
        }
        return content;
    }

    //长文本数组翻译方法
    public static String[] translate(String[] text, String lanFrom, String lanTo) {
        if (text == null || text.length < 1) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < text.length; i++) {
            if (i < text.length - 1) {
                sb.append(text[i]).append("BBaaBB");
            } else {
                sb.append(text[i]);
            }
        }
        String translatedText = (sb.toString().getBytes().length >= 4000) ? translate(
                sb.toString(), lanFrom, lanTo)
                : googleApiTranslate(sb.toString(), lanFrom, lanTo);
        return translatedText.split("BBaaBB", -2);
    }

    //短文本翻译方法
    public static String googleApiTranslate(String sentence, String from,
            String to) {
        Translate.setHttpReferrer("http://www.boling.cn");
        String translatedText = "";
        try {
            translatedText = Translate.execute(sentence, Language.fromString(from), Language.fromString(to));// Language.ENGLISH,
        } catch (Exception ex) {
        }
        return translatedText;
    }

    //短文本数组翻译方法
    public static String[] googleApiTranslateArray(String[] sentence, String from,
            String to) {
        Translate.setHttpReferrer("http://www.boling.cn");
        String[] translatedText = null;
        try {
            translatedText = Translate.execute(sentence, Language.fromString(from), Language.fromString(to));// Language.ENGLISH,
        } catch (Exception ex) {
        }
        return translatedText;
    }

    public static void main(String[] args) {
        String[] orig = {"调试问题答案1。", "调试问题答案2。", "调试问题答案3。"};
        String[] tran = translate(orig, "zh-CN", "en");
        for (int i = 0; i < tran.length; i++) {
            System.out.println("orig[" + i + "]=" + orig[i]);
            System.out.println("tran[" + i + "]=" + tran[i]);
        }
    }
}
